package com.dhc.redpacket.service.Imp;

import com.dhc.redpacket.dao.RedPacketDao;
import com.dhc.redpacket.dao.UserRedPacketDao;
import com.dhc.redpacket.pojo.RedPacket;
import com.dhc.redpacket.pojo.UserRedPacket;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dhc.redpacket.service.UserRedPacketService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserRedPacketServiceImp implements UserRedPacketService {

	private Logger logger = Logger.getLogger(UserRedPacketServiceImp.class);

	@Autowired
	private UserRedPacketDao userRedPacketDao = null;

	@Autowired
	private RedPacketDao redPacketDao = null;

	@Override
	@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int grapRedPacket(Long redPacketId, Long userId) throws Exception {
		RedPacket packet = redPacketDao.getRedPacket(redPacketId);
		if (packet.getStock() > 0) {
			// 扣减红包数
			redPacketDao.decreaseRedPacket(redPacketId);

			// 生成红包
			UserRedPacket userRedPacket = new UserRedPacket();
			userRedPacket.setRedPacketId(redPacketId);
			userRedPacket.setUserId(userId);
			userRedPacket.setAmount(packet.getUnitAmount());
			userRedPacket.setNote("抢红包-" + redPacketId);
			int i = userRedPacketDao.grapRedPacket(userRedPacket);
			return i;
		}
		// 返回失败
		return 0;
	}

	@Override
	public int grapRedPacketForVersion(Long redPacketId, Long userId) throws Exception {
		long start = System.currentTimeMillis();
		while (true) {
			long end = System.currentTimeMillis();
			if (end - start > 100) {
				return -2;
			}
			RedPacket packet = redPacketDao.getRedPacket(redPacketId);
			// 还有红包
			if (packet.getStock() > 0) {
				// 扣减红包数
				int num = redPacketDao.decreaseRedPacketForVersion(redPacketId, packet.getVersion());
				if (num == 0) {
					logger.info("扣减失败============================================");
					continue;
				}

				// 生成红包
				UserRedPacket userRedPacket = new UserRedPacket();
				userRedPacket.setRedPacketId(redPacketId);
				userRedPacket.setUserId(userId);
				userRedPacket.setAmount(packet.getUnitAmount());
				userRedPacket.setNote("抢红包-" + redPacketId);
				int i = userRedPacketDao.grapRedPacket(userRedPacket);
				return i;
			}
			return 0;
		}
	}
}
